package com.zyh.kafka.day03;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.util.Arrays;
import java.util.Properties;

public class TranscationConsumerTest {
    public static void main(String[] args) {
        //1 配置消费者参数
        Properties consumerConfigs = new Properties();
        consumerConfigs.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"kafka24:9092");
        consumerConfigs.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        consumerConfigs.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        consumerConfigs.setProperty(ConsumerConfig.GROUP_ID_CONFIG,"g4");
        // 设置隔离性为-读已提交
        consumerConfigs.setProperty(ConsumerConfig.ISOLATION_LEVEL_CONFIG,"read_committed");
        //2 创建消费者
        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(consumerConfigs);
        //3 订阅topic
        kafkaConsumer.subscribe(Arrays.asList("topic-a","topic-b"));
        //4 拉取消息
        try {
            while (true){
                ConsumerRecords<String, String> records = kafkaConsumer.poll(1000);
                //5 处理消息
                for (ConsumerRecord<String, String> record : records) {
                    System.out.println("record = " + record);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //6 关闭消费者
            kafkaConsumer.close();
        }
    }
}
